package com.hongri.recyclerview.fragment;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.hongri.recyclerview.R;
import com.hongri.recyclerview.thread.PausableThreadPoolExecutor;
import com.hongri.recyclerview.utils.Logger;
import com.hongri.recyclerview.utils.ThreadPoolUtils;

/**
 * @author：zhongyao on 2017/4/25
 * @description:线程池test 参考：
 * http://www.cnblogs.com/whoislcj/p/5607734.html
 * <p>
 * <p>
 * add:
 * 线程池最好不使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。
 * 说明：Executors返回的线程池对象的弊端如下：
 * 1）FixedThreadPool和SingleThreadPool:
 *   允许的请求队列长度为Integer.MAX_VALUE，可能会堆积大量的请求，从而导致OOM。
 * 2）CachedThreadPool和ScheduledThreadPool:
 *   允许的创建线程数量为Integer.MAX_VALUE，可能会创建大量的线程，从而导致OOM。
 */
public class ThreadPoolFragment extends Fragment {

    private static ThreadPoolFragment threadPoolFragment;
    private String TAG = ThreadPoolFragment.class.getSimpleName();

    private ExecutorService executorService;
    private Button resume_or_pause;
    private ThreadPoolUtils threadPoolUtils;

    Runnable command = new Runnable() {
        @Override
        public void run() {
            Logger.d("command");
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Logger.d("刷新界面");
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(receiver, filter);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_thread_pool, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);

        //创建一个可重用固定线程数的线程池，以共享的无界队列方式来运行这些线程。
        executorService = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 20; i++) {
            Runnable syncRunnable = new Runnable() {
                @Override
                public void run() {
                    Logger.d(TAG + "---" + Thread.currentThread().getName());
                }
            };
//            executorService.execute(syncRunnable);
        }
//        executorService.execute(command);

        //创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程。（比较适合执行大量耗时较少的任务）
        executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
            Runnable syncRunnable = new Runnable() {
                @Override
                public void run() {
                    Logger.d(TAG + "---" + Thread.currentThread().getName());
                }
            };
//            executorService.execute(syncRunnable);
        }

        //创建一个定长线程池，支持定时及周期性任务执行
        executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 20; i++) {
            Runnable syncRunnable = new Runnable() {
                @Override
                public void run() {
                    Logger.d(TAG + "---" + Thread.currentThread().getName());
                }
            };
            //2000ms后执行syncRunnable
//            executorService.schedule(syncRunnable,2000, TimeUnit.MILLISECONDS);
            //延迟10m后每隔2000ms执行一次syncRunnable
            executorService.execute(syncRunnable);
        }

        //创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
        for (int i = 0; i < 20; i++) {
            Runnable syncRunnable = new Runnable() {
                @Override
                public void run() {
                    Logger.d(TAG + "---" + Thread.currentThread().getName());
                }
            };
            //2000ms后执行syncRunnable
//            executorService.schedule(syncRunnable,2000, TimeUnit.MILLISECONDS);
            //延迟10m后每隔2000ms执行一次syncRunnable
//            executorService.scheduleAtFixedRate(syncRunnable,10,2000,TimeUnit.MILLISECONDS);
        }


        threadPoolUtils = new ThreadPoolUtils();
//        threadPoolUtils.executeMethod();
        threadPoolUtils.executePausableMethod();
    }

    private void initView(View view) {
        resume_or_pause = (Button) view.findViewById(R.id.resume_or_pause);

        resume_or_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PausableThreadPoolExecutor.isPaused) {
                    threadPoolUtils.isResume();
                    PausableThreadPoolExecutor.isPaused = false;
                } else {
                    threadPoolUtils.isPause();
                    PausableThreadPoolExecutor.isPaused = true;
                }
            }
        });
    }

    public static ThreadPoolFragment getInstance() {
        if (threadPoolFragment == null) {
            threadPoolFragment = new ThreadPoolFragment();
        }
        return threadPoolFragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (receiver != null) {
            getActivity().unregisterReceiver(receiver);
        }
    }
}
